from django import shortcuts
from django.contrib.auth import models as auth_models
from django.views.generic import list_detail
from tagging import models as tag_models
import datetime
from coolblog import models

def get_base_context():
    context = {
        'blog': models.Blog.instance,
        'category_list': models.Category.objects.all,
        'archive_list': models.Archive.objects.all,
        'recent_articles': models.Article.get_recent_list
    }

    return context

def index(request):
    queryset = models.Article.get_all()
    return view_list(request, queryset)

def view_article(request, slug):
    article = models.Article.objects.get(slug=slug)
    context = shortcuts.RequestContext(request, get_base_context())
    context['article'] = article

    return shortcuts.render_to_response('frontend/article.html', context)

def view_category(request, slug):
    category = models.Category.objects.get(slug=slug)
    queryset = models.Article.objects.filter(category=category)
    
    return view_list(request, queryset, category)

def view_author(request, username):
    author = auth_models.User.objects.get(username=username)
    queryset = models.Article.objects.filter(author=author)
    
    return view_list(request, queryset, author)

def view_tag(request, tag):
    queryset = tag_models.TaggedItem.objects.get_by_model(
        models.Article, tag)
    return view_list(request, queryset, tag)

def view_archive(request, year, month):
    archive = models.Archive(year=int(year), month=int(month))
    queryset = models.Article.objects.filter(
        publish_date__year=year, publish_date__month=month)
    return view_list(request, queryset, archive)

def view_list(request, queryset, instance=None):
    """
    View a list of articles. All links that show article list
    should call this function.
    """
    if 'page' in request.GET:
        page = request.GET['page']
    else:
        page = 1

    context = get_base_context()
    if instance:
        context['title'] = instance

    return list_detail.object_list(
        request,
        queryset=queryset,
        template_name='frontend/index.html',
        template_object_name='article',
        extra_context=context,
        page=page,
        paginate_by=models.Blog.instance().entries_per_page
    )

def page_not_found(request):
    """
    custom 404 page
    """
    context = shortcuts.RequestContext(request, get_base_context())
    return shortcuts.render_to_response('frontend/404.html', context)
